package com.googlecode.lucenedb.lucene;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import junit.framework.TestCase;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.CachingCollector;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.grouping.GroupDocs;
import org.apache.lucene.search.grouping.SearchGroup;
import org.apache.lucene.search.grouping.TermFirstPassGroupingCollector;
import org.apache.lucene.search.grouping.TermSecondPassGroupingCollector;
import org.apache.lucene.search.grouping.TopGroups;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class LuceneGroup extends TestCase {

	public void testGroup() throws Exception {
		StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_33);
		Directory directory = FSDirectory
				.open(new File("d:/lucenedbindex/test"));
		IndexSearcher is = new IndexSearcher(directory);
		QueryParser parser = new QueryParser(Version.LUCENE_33, "name",
				analyzer);
		Query query = parser.parse("( age:[20 TO 21]  ) ");

		TermFirstPassGroupingCollector c1 = new TermFirstPassGroupingCollector(
				"age", Sort.RELEVANCE, 100);

		int maxDocsPerGroup = 100;
		int groupOffset = 0;
		boolean cacheScores = true;
		double maxCacheRAMMB = 4.0;
		int withinGroupOffset = 0;
		CachingCollector cachedCollector = CachingCollector.create(c1,
				cacheScores, maxCacheRAMMB);
		is.search(query, cachedCollector);
		Collection<SearchGroup<String>> topGroups = c1.getTopGroups(
				groupOffset, true);

		if (topGroups == null) {
			return;
		}

		TermSecondPassGroupingCollector c2 = new TermSecondPassGroupingCollector(
				"age", topGroups, Sort.RELEVANCE, Sort.RELEVANCE,
				maxDocsPerGroup, true, true, true);

		if (cachedCollector.isCached()) {
			cachedCollector.replay(c2);
		} else {
			is.search(query, c2);
		}
		
		TopGroups<String> tg = c2.getTopGroups(withinGroupOffset);
	    GroupDocs<String>[] gds = tg.groups;
		for(GroupDocs<String> gd : gds) {
			System.out.println(gd.groupValue+"   "+gd.totalHits);
		}
	

	}

}
